#include "library.h"

// 加载数据
void load_data()
{
    FILE *fp;

    // 1. 加载用户数据
    fp = fopen("users.dat", "rb");
    if (fp)
    {
        User temp_user;
        while (fread(&temp_user, sizeof(User), 1, fp) == 1)
        {
            User *new_user = malloc(sizeof(User));
            if (!new_user)
            {
                perror("内存分配失败");
                continue;
            }

            // 复制数据并初始化链表
            memcpy(new_user, &temp_user, sizeof(User));
            INIT_LIST_HEAD(&new_user->borrowed_books);
            INIT_LIST_HEAD(&new_user->list);

            // 添加到用户列表
            list_add_tail(&new_user->list, &user_list);
        }
        fclose(fp);
    }

    // 2. 加载图书数据
    fp = fopen("books.dat", "rb");
    if (fp)
    {
        Book temp_book;
        while (fread(&temp_book, sizeof(Book), 1, fp) == 1)
        {
            Book *new_book = malloc(sizeof(Book));
            if (!new_book)
            {
                perror("内存分配错误");
                continue;
            }

            // 复制数据
            memcpy(new_book, &temp_book, sizeof(Book));
            INIT_LIST_HEAD(&new_book->list);
            
            // 添加到图书链表
            list_add_tail(&new_book->list, &book_list);
        }
        fclose(fp);
    }

    // 3. 加载借阅关系
    fp = fopen("borrows.dat", "r");
    if (fp)
    {
        char user_id[20], book_id[20];
        time_t borrow_time;
        
        while (fscanf(fp, "%19s %19s %ld", user_id, book_id, &borrow_time) == 3)
        {
            // 查找用户
            User *user = NULL;
            list_for_each_entry(user, &user_list, list)
            {
                if (strcmp(user->id, user_id) == 0)
                    break;
            }
            
            if (user)
            {
                BorrowRecord *record = malloc(sizeof(BorrowRecord));
                if (record)
                {
                    strncpy(record->book_id, book_id, sizeof(record->book_id));
                    record->borrow_time = borrow_time;
                    INIT_LIST_HEAD(&record->list);
                    list_add_tail(&record->list, &user->borrowed_books);
                }
            }
        }
        fclose(fp);
    }
}

// 保存数据
void save_data()
{
    FILE *fp;

    // 保存用户数据
    fp = fopen("users.dat", "wb");
    if (fp)
    {
        User *user;
        list_for_each_entry(user, &user_list, list)
        {
            // 不保存链表指针，只保存有效数据
            User save_user = *user;
            save_user.borrowed_books.next = NULL;
            save_user.borrowed_books.prev = NULL;
            save_user.list.next = NULL;
            save_user.list.prev = NULL;
            
            fwrite(&save_user, sizeof(User), 1, fp);
        }
        fclose(fp);
    }

    // 保存图书数据
    fp = fopen("books.dat", "wb");
    if (fp)
    {
        Book *book;
        list_for_each_entry(book, &book_list, list)
        {
            // 不保存链表指针
            Book save_book = *book;
            save_book.list.next = NULL;
            save_book.list.prev = NULL;
            
            fwrite(&save_book, sizeof(Book), 1, fp);
        }
        fclose(fp);
    }
    
    // 保存借阅关系
    fp = fopen("borrows.dat", "w");
    if (fp)
    {
        User *user;
        list_for_each_entry(user, &user_list, list)
        {
            if (!list_empty(&user->borrowed_books))
            {
                BorrowRecord *record;
                list_for_each_entry(record, &user->borrowed_books, list)
                {
                    fprintf(fp, "%s %s %ld\n", user->id, record->book_id, record->borrow_time);
                }
            }   
        }
        fclose(fp);
    }
}



// 主菜单页面
void show_main_menu()
{
    printf("\n=== 图书馆管理系统 ===\n");
    printf("1.登录\n");
    printf("2.注册\n");
    printf("3.访客浏览\n");
    printf("4.退出\n");
    printf("\n=== 请选择操作(1-4): ===\n");
}

// 登录页面
void login_menu()
{
    int choice;
    do
    {
        printf("\n=== 登录 ===\n");
        printf("1. 管理员登录\n");
        printf("2. 读者登录\n");
        printf("3. 返回主菜单\n");
        printf("请选择操作(1-3): ");
        
        if (scanf("%d", &choice) != 1) {
            clear_input_buffer();
            printf("无效输入，请输入数字\n");
            continue;
        }
        clear_input_buffer();
        
        switch (choice)
        {
        case 1:
            admin_login();
            break;
        case 2:
            reader_login();
            break;
        case 3:
            return;
        default:
            printf("无效输入\n");
        }
    } while (1);
}

// 注册页面
void register_menu()
{
    int choice;
    do
    {
        printf("\n=== 注册 ===\n");
        printf("1. 管理员注册\n");
        printf("2. 读者注册\n");
        printf("3. 返回主菜单\n");
        printf("请选择操作(1-3): ");
        
        if (scanf("%d", &choice) != 1) {
            clear_input_buffer();
            printf("无效输入，请输入数字\n");
            continue;
        }
        clear_input_buffer();
        
        switch (choice)
        {
        case 1:
            admin_register();
            break;
        case 2:
            reader_register();
            break;
        case 3:
            return;
        default:
            printf("无效输入\n");
        }
    } while (1);
}

// 管理员页面
void admin_menu()
{
    int choice;
    do
    {
        printf("\n=== 管理员菜单 ===\n");
        printf("1. 读者信息管理\n");
        printf("2. 删除用户信息\n");
        printf("3. 图书信息查看\n");
        printf("4. 增删改查图书信息\n");
        // printf("5. 借阅统计\n");
        printf("5. 退出登录\n");
        printf("请选择操作 (1-5): \n");
        
        if (scanf("%d", &choice) != 1) {
            clear_input_buffer();
            printf("无效输入，请输入数字\n");
            continue;
        }
        clear_input_buffer();

        switch (choice)
        {
        case 1:
            show_all_users();
            break;
        case 2:
            delete_user();
            break;
        case 3:
            show_all_books();
            break;
        case 4:
            book_management();
            break;
        // case 5:
        //     // show_book_stats();
        //     break;
        case 5:
            current_user = NULL;
            printf("已退出管理员账号\n");
            return; // 添加返回语句
        default:
            printf("无效操作\n");
        }
    } while (1);
}

// 读者页面
void reader_menu()
{
    int choice;
    do
    {
        printf("\n=== 读者菜单 ===\n");
        printf("1. 图书浏览\n");
        printf("2. 借阅图书\n");
        printf("3. 归还图书\n");
        printf("4. 借阅记录\n");
        printf("5. 返回上一级菜单\n");
        printf("请选择操作 (1-5): ");
        
        if (scanf("%d", &choice) != 1) {
            clear_input_buffer();
            printf("无效输入，请输入数字\n");
            continue;
        }
        clear_input_buffer();

        switch (choice)
        {
        case 1:
            show_all_books();
            break;
        case 2:
            borrow_book();
            break;
        case 3:
            return_book();
            break;
        case 4:
            show_borrowed_books();
            break;
        case 5:
            current_user = NULL;
            printf("已退出读者账号\n");
            return;
        default:
            printf("无效选择，请重新输入！\n");
        }
    } while (1);
}

void clear_input_buffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

int main(int argc, char const *argv[])
{
    load_data();

    int choice;
    do
    {
        show_main_menu();

        if (scanf("%d", &choice) != 1) {
            clear_input_buffer();
            printf("无效输入，请输入数字\n");
            continue;
        }
        clear_input_buffer();
        
        switch (choice)
        {
        case 1:
            login_menu();
            break;
        case 2:
            register_menu();
            break;
        case 3:
            guest_browse();
            break;
        case 4:
            save_data();
            printf("已保存退出!\n");
            exit(0);
        default:
            printf("无效输入\n");
            break;
        }
    } while (1);

    return 0;
}
